import React, { Fragment, PureComponent } from 'react'
import { Input, Button, Form, Row, Col, Radio, Select, Table, Divider,DatePicker,message } from 'antd';
import { connect } from 'dva'
import PropTypes from 'prop-types';
import moment from 'moment';
import * as R from 'ramda'
import VehicleDetailMsgModal from '../../modals/msgModal';
import PateoStandardTable from '@/common/PateoTable/PateoStandardTable'
import PateoSearchNewForm from '@/common/PateoTable/PateoSearchForm/PateoSearchNewForm'
import * as G from '@/utils/common'
import {findDicByCodeSort, getDicByKey} from '@/support/common';
import styles from '../../style.less'


const { RangePicker } = DatePicker;
const { TextArea } = Input;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
let vinNumber = '';
let pdsn = '';
let tbox = '';

// @Form.create()
@connect(({ common, loading, user }) => ({
  common,
  loading: loading.models.common,
  user,
}))
export default class TboxTimeScaledTab extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.array,
    authButton: PropTypes.array,
  };
  state = {
    msgVisible: false,
    msg: '',
    projectId: '',
    deviceId: '',
    dataType: 'originalDm',
    formValues: {
      startTime: moment()
        .add(-1, 'days')
        .format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    },
    initTimeValue: {
      startTime: moment()
        .add(-1, 'days')
        .format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    },
  };

  componentDidMount() {
    const { rowData, projectId, dispatch } = this.props;
    vinNumber = rowData.vin;
    pdsn = rowData.pdsn;
    tbox= rowData.tbox;
    const { formValues, dataType } = this.state
    this.setState({
      projectId,
      deviceId: vinNumber,
    })
    dispatch({
      type: 'common/pagePost',
      payload: { url: '/vehicle/selectTboxDeviceDataLog', projectId,dataType,
        deviceId: vinNumber,
        ...formValues
      },
    });
  }

  handleOpenMsg = (value) => {
    const { rowData } = this.props;
    const obj = value;
    obj.vin = vinNumber;
    obj.colletionDataTime = value.ngtpCreateTime;
    obj.receiveDataTime = moment(parseInt(value.createtime)).format('YYYY-MM-DD HH:mm:ss');
    obj.messageType = value.msgType;
    obj.content = JSON.stringify(value);
    this.setState({ msgVisible: true, msg: obj });
  }

  handleCloseMsg = () => {
    this.setState({ msgVisible: false });
  }

  handleFormReset = (form) => {
    form.resetFields();
    this.setState({
      formValues: {
        startTime: moment()
          .add(-1, 'days')
          .format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      },
      initTimeValue: {
        startTime: moment()
          .add(-1, 'days')
          .format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      },
    });
  }

  /**
   * 参数校验
   * @param fieldsValue
   */
  dataFormat = fields => {
    if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
      let day = getDicByKey(this.context.dicData, 'tsdb', 'day');
      let duration = getDicByKey(this.context.dicData, 'tsdb', 'duration');

      const [start, end] = fields.handleTimeRange;
      fields['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
      fields['endTime'] = moment(end).format('YYYY-MM-DD HH:mm:ss');
      delete fields['handleTimeRange'];
      if (day !== '-1') {
        if (moment(fields.startTime).isBefore(moment().subtract(day, 'days'))){
          message.warning(`只能查询最近${day}天的数据！`);
          return false;
        }
      }
      if (moment(fields.startTime).isAfter(moment().format('YYYY-MM-DD 23:59:59'))) {
        message.warning('开始时间不能超过今天！');
        return false;
      } else if (moment(fields.startTime).isBefore(moment(fields.endTime).subtract(duration, 'days'))) {
        message.warning(`查询区间为${duration}天！`);
        return false;
      }  else {
        return fields;
      }
    } else {
      message.warning('请选择时间！');
      return false;
    }
  };

  handleTableChange = (pagination, filters) => {
    const { dispatch } = this.props;
    const { formValues, projectId, deviceId } = this.state;
    const { current, pageSize } = pagination;
    const params = {
      page:current,
      size: pageSize,
      ...formValues,
      ...filters,
      projectId,
      deviceId,
    };
    dispatch({
      type:'common/pagePost',
      payload: { url: '/vehicle/selectTboxDeviceDataLog', ...params },
    });
  };

  render() {
    const { msgVisible, msg , deviceId, projectId, initTimeValue ,formValues} = this.state
    const {common: { data: { list, pagination } }, loading,} = this.props
    const searchItems = [
      {
        title: '是否是原始报文',
        specialStyle:8,
        type: 'select',
        key: 'dataType',
        initialValue: 'originalDm',
        selectOptions: findDicByCodeSort(this.context.dicData, 'tboxTimeScaledDataType'),
        keyValue: ['dictKey', 'dictValue'],
      },
      {
        title: 'serviceType',
        specialStyle:8,
        type: 'select',
        key: 'serviceType',
        selectOptions: findDicByCodeSort(this.context.dicData, 'tboxTimeScaledServiceType'),
        keyValue: ['dictKey', 'dictValue'],
      }, {
        title: 'messageType',
        specialStyle:10,
        type: 'select',
        key: 'messageType',
        selectOptions:findDicByCodeSort(this.context.dicData, 'tboxTimeScaledMessageType'),
        keyValue: ['dictKey', 'dictValue'],
      }, {
        title: '时间',
        type: 'rangePicker',
        key: 'handleTimeRange',
        style: { width: '100%' },
        specialStyle:12,
        initialValue: [moment(initTimeValue.startTime), moment(initTimeValue.endTime)],
        rules: [{ required: true, message: '时间必选!' }],
      }, ]
    const columns = [
      {
        title: 'messageId',
        dataIndex: 'messageID',
        render: (text, record) => {
          return text? text: (record.serviceId ? record.serviceId : '');
        },
      },
      {
        title: 'serviceType',
        dataIndex: 'serviceType',
      }, {
        title: 'messageType',
        dataIndex: 'msgType',
      }, {
        title: 'serviceId',
        dataIndex: 'serviceId',
      }, {
        title: 'colletionDataTime',
        dataIndex: 'ngtpCreateTime',
        render: (text, record) => {
          return text? text: (record['data.collectionTime'] ? record['data.collectionTime'] : '');
        },
      }, {
        title: '操作',
        dataIndex: '',
        render: (text, record) => {
          return <a onClick={()=>this.handleOpenMsg(record)}>详情</a>;
        },
      }
    ]
    return (
      <div>
        <PateoSearchNewForm
          ref={unit => this.unit = unit}
          searchItems={searchItems}
          fetchUrl='common/pagePost'
          payloadUrl={{ url: '/vehicle/selectTboxDeviceDataLog', deviceId, projectId}}
          saveFormValues={val => this.setState({ formValues: {...Object.assign(formValues, val),deviceId,projectId} })}
          handleFormReset={this.handleFormReset}
          handleFieldsValue={this.dataFormat}
          params={
            {startTime: moment()
              .add(-1, 'days')
              .format('YYYY-MM-DD HH:mm:ss'),
              endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
              dataType: 'originalDm'
            }
          }
        />
        <Table
          size={'small'}
          rowKey={record => record.sid}
          dataSource={list}
          loading={loading}
          columns={columns}
          pagination={G.paginationProps(pagination)}
          onChange={this.handleTableChange}
        />
        <VehicleDetailMsgModal
          msgVisible={msgVisible}
          msg={msg}
          handleCloseMsg={this.handleCloseMsg}
        />
      </div>
    );
  }
}
